#include "messagehandler.h"
#include "tcp_message.h"
#include <iostream>
#include "loghelper.h"
#include "message_types_res.h"
#include "json_message_processor.h"
#include "utility.hpp"
#include <thread>

using namespace std;
using namespace RockLog;
using namespace boost::property_tree;

static JsonMessageProcessor s_jsonMessageProcessor;

MessageHandler::MessageHandler(const MessageType_t &messageTypes)
    : _messageTypes(messageTypes)
{
}

void MessageHandler::start()
{
}


void MessageHandler::readBody(TcpSessionMessage_t msg)
{
    LOG(kDebug) << "msg.msgType: " << msg.tcpMessage.msgType << std::endl
        << "msg.body: " << msg.tcpMessage.body << std::endl;
   
    TcpMessage_t m;
    if (_messageTypes[kHeartReq] == msg.tcpMessage.msgType)
    {
        m = onHeartReq(msg.tcpMessage);
    }
    else if (_messageTypes[kLoginReq] == msg.tcpMessage.msgType)
    {
        m = onLoginReq(msg.tcpMessage);
    }
    else if (_messageTypes[kLogoutReq] == msg.tcpMessage.msgType)
    {
        m = onLogoutReq(msg.tcpMessage);
    }

    if (m.msgType > 0)
    {
        TcpSessionMessage_t msgRsp;
        msgRsp.tcpMessage = m;
        msgRsp.sessionId = msg.sessionId;
        sendTcpMessageSignal(msgRsp);
    }
}

TcpMessage_t MessageHandler::onHeartReq(const TcpMessage_t& msg)
{
    TcpMessage_t m;
    m.syncBytes = msg.syncBytes;
    HeartbeatRsp_t rsp;
    rsp.code = 1000;
    m.body = s_jsonMessageProcessor.encodeHeartbeatRsp(rsp);

    m.msgType = _messageTypes[kHeartRsp];
    return m;
}


TcpMessage_t MessageHandler::onLoginReq(const TcpMessage_t& msg)
{
    LoginRsp_t rsp;
    LoginReq_t req;

    LOG(kDebug) << "receive login req" << std::endl;


    bool ret = s_jsonMessageProcessor.decodeLoginReq(msg.body, req);
    if (!ret)
    {
        rsp.code = CODE_MSG_RESOLVE_FAIL;
        rsp.message = "Fail to resolve the login_req";
        LOG(kErr) << rsp.message << std::endl;
    }
    else
    {
        rsp.code = CODE_SUCCESS;
    }
    
    TcpMessage_t m;
    m.body = s_jsonMessageProcessor.encodeLoginRsp(rsp);
    m.msgType = _messageTypes[kLoginRsp];
    return m;
}

TcpMessage_t MessageHandler::onLogoutReq(const TcpMessage_t& msg)
{
    LogoutRsp_t rsp;
    LOG(kDebug) << "receive logout req" << std::endl;

    rsp.code = CODE_SUCCESS;

    TcpMessage_t m;
    m.body = s_jsonMessageProcessor.encodeLogoutRsp(rsp);
    m.msgType = _messageTypes[kLogoutRsp];
    return m;
}

